package com.example.simplecardbasic.Utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.example.simplecardbasic.enums.ResultEnum;
import com.example.simplecardbasic.exception.CreditException;
import com.google.gson.Gson;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class SmsUtil {

    static final String product="Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";
    static final String accessKeyId = "LTAIZWWiPmzD06Sb";
    static final String accessKeySecret = "i11N2R7mO0VxWuDs82NFnPaRgM7DUs";

    static final String signName = "面条博客";

    static final String templateCode = "SMS_126910076";

    static final Integer timeLimit = 240;

    static final Integer codeTime = 300;

    public static SendSmsResponse sendSms(String phone, StringRedisTemplate redisTemplate) throws ClientException{

        if(redisTemplate.hasKey(phone)) {
            if(redisTemplate.getExpire(phone) > timeLimit) {
                throw new CreditException(ResultEnum.SMS_TIME_LIMIT);
            }
        }

        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        Map<String,String> map = new HashMap<>();
        String code = makeCode();
        map.put("code",code);
        map.put("product","dsd");
        Gson gson = new Gson();
        request.setTemplateParam(gson.toJson(map));
        request.setOutId("yourOutId");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //存入缓存
            redisTemplate.opsForValue().set(phone,code,codeTime, TimeUnit.SECONDS);
        }else {
            throw new CreditException(ResultEnum.SMS_SEND_FAILED);
        }
        return sendSmsResponse;
    }


    public static String makeCode() {
        String code = "";
        for(int i=0; i<4; i++) {
            code = code + (int)(Math.random() * 9);
        }
        return String.valueOf(code);
    }
}
